<script setup>
import {onMounted, reactive, ref} from 'vue'
import {ElMessage, ElMessageBox} from 'element-plus'
import http from "@/request/http.js";
import {useRoute, useRouter} from 'vue-router'
import {Management} from "@element-plus/icons-vue";

const route = useRoute()
const router = useRouter()

// 登录状态检查
const isLoggedIn = () => {
  const isLogged = sessionStorage.getItem('isLogged')
  const token = sessionStorage.getItem('token')
  return isLogged === 'true' && !!token
}

// 页面状态管理
const activeMenu = ref('goods-list')
const handleMenuSelect = (index) => {
  activeMenu.value = index
}
const levelOptions = ref([
  {label: '1级', value: 1},
  {label: '2级', value: 2},
  {label: '3级', value: 3},
  {label: '4级', value: 4},
  {label: '5级', value: 5}
])

// 表格数据与分页
const tableData = ref([])
const total = ref(0)
const pageNum = ref(1)
const pageSize = ref(10)
const searchKey = ref('')  // 搜索关键词

// 弹窗与表单数据
const dialogVisible = ref(false)
const dialogTitle = ref('新增商品')
const formRef = ref(null)

const formData = reactive({
  goodsId: null,
  goodsName: '',
  pointsNeeded: null,
  levelLimit: 1,
  stock: 0,
  status: 1
})

// 表单验证规则
const formRules = reactive({
  goodsName: [{required: true, message: '商品名称不能为空', trigger: 'blur'}],
  pointsNeeded: [
    {required: true, message: '所需积分不能为空', trigger: 'blur'},
    {type: 'number', min: 1, message: '积分必须大于0', trigger: 'blur'}
  ],
  levelLimit: [{type: 'number', min: 1, message: '等级限制至少为1', trigger: 'blur'}],
  stock: [{type: 'number', min: 0, message: '库存不能为负数', trigger: 'blur'}],
  status: [{required: true, message: '请选择商品状态', trigger: 'change'}]
})

// 初始化加载
onMounted(() => {
  if (!isLoggedIn()) {
    ElMessage.warning('请先登录')
    router.push('/login')
  } else {
    fetchGoodsList()
  }
})

// 获取商品列表
const fetchGoodsList = async () => {
  try {
    const url = searchKey.value ? '/points/admin/mall/goods/search' : '/points/admin/mall/goods'

    const res = await http.get(url, {
      params: {
        pageNum: pageNum.value,
        pageSize: pageSize.value,
        goodsName: searchKey.value
      }
    })

    if (res.code === 200) {
      tableData.value = res.data.records
      total.value = res.data.total
    } else {
      ElMessage.error(res.msg || '获取商品列表失败')
    }
  } catch (error) {
    ElMessage.error('网络错误：' + error.message)
  }
}

// 分页处理
const handleSizeChange = (val) => {
  pageSize.value = val
  fetchGoodsList()
}

const handleCurrentChange = (val) => {
  pageNum.value = val
  fetchGoodsList()
}

// 搜索与重置
const handleSearch = () => {
  pageNum.value = 1
  fetchGoodsList()
}

const resetSearch = () => {
  searchKey.value = ''
  pageNum.value = 1
  fetchGoodsList()
}

// 新增商品
const handleAdd = () => {
  formRef.value?.resetFields()
  formData.goodsId = null
  formData.status = 1
  formData.levelLimit = 1
  dialogTitle.value = '新增商品'
  dialogVisible.value = true
}

// 编辑商品
const handleEdit = (row) => {
  Object.assign(formData, row)
  dialogTitle.value = '编辑商品'
  dialogVisible.value = true
}

// 提交表单
const handleSubmit = async () => {
  try {
    await formRef.value.validate()
    if (formData.goodsId) {
      await http.put('/points/admin/mall/goods', formData)
      ElMessage.success('商品编辑成功')
    } else {
      await http.post('/points/admin/mall/goods', formData)
      ElMessage.success('商品添加成功')
    }
    dialogVisible.value = false
    fetchGoodsList()
  } catch (error) {
    ElMessage.error(error.response?.data?.msg || error.message)
    return false
  }
}

// 状态变更
const handleStatusChange = async (row) => {
  try {
    await ElMessageBox.confirm(
        `确定要将商品【${row.goodsName}】${row.status === 1 ? '下架' : '上架'}吗？`,
        '状态修改',
        {confirmButtonText: '确定', cancelButtonText: '取消', type: row.status === 1 ? 'warning' : 'success'}
    )
    await http.put('/points/admin/mall/goods', {
      goodsId: row.goodsId,
      status: row.status === 1 ? 0 : 1
    })
    ElMessage.success(`商品已${row.status === 1 ? '下架' : '上架'}`)
    fetchGoodsList()
  } catch (error) {
    if (error.name !== 'CanceledError') {
      ElMessage.error(error.response?.data?.msg || '状态修改失败')
    }
  }
}
</script>

<template>
  <div class="goods-management-container">
    <!-- 页面标题 -->
    <div class="page-header">
      <h2>商品管理</h2>
    </div>

    <!-- 操作栏 -->
    <div class="operation-bar">
      <el-button type="primary" @click="handleAdd">
        <Management style="margin-right: 5px"/>
        新增商品
      </el-button>

      <!-- 搜索区域 -->
      <div class="search-group">
        <el-input
            v-model="searchKey"
            class="search-input"
            placeholder="请输入商品名称搜索"
            @keyup.enter="handleSearch"
        ></el-input>
        <el-button type="primary" @click="handleSearch">搜索</el-button>
        <el-button @click="resetSearch">重置</el-button>
      </div>
    </div>

    <!-- 商品列表 -->
    <el-card class="content-card">
      <el-table
          :data="tableData"
          border
          style="width: 100%"
      >
        <el-table-column label="商品ID" prop="goodsId" width="100"/>
        <el-table-column label="商品名称" prop="goodsName"/>
        <el-table-column label="所需积分值" prop="pointsNeeded" width="120"/>
        <el-table-column label="等级限制" prop="levelLimit" width="120">
          <template #default="scope">
            {{ scope.row.levelLimit }}级
          </template>
        </el-table-column>
        <el-table-column label="库存数量" prop="stock" width="100"/>
        <el-table-column label="状态" prop="status" width="100">
          <template #default="scope">
            <el-tag :type="scope.row.status === 1 ? 'success' : 'danger'">
              {{ scope.row.status === 1 ? '上架' : '下架' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="300">
          <template #default="scope">
            <el-button
                size="small"
                type="primary"
                @click="handleEdit(scope.row)"
            >
              编辑
            </el-button>
            <el-button
                :type="scope.row.status === 1 ? 'warning' : 'success'"
                size="small"
                @click="handleStatusChange(scope.row)"
            >
              {{ scope.row.status === 1 ? '下架' : '上架' }}
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination" style="margin-top: 15px; text-align: right">
        <el-pagination
            v-model:current-page="pageNum"
            v-model:page-size="pageSize"
            :page-sizes="[10, 20, 50]"
            :total="total"
            layout="total, sizes, prev, pager, next, jumper"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
        />
      </div>
    </el-card>

    <!-- 商品表单弹窗 -->
    <el-dialog
        v-model="dialogVisible"
        :title="dialogTitle"
        width="600px"
    >
      <el-form
          ref="formRef"
          :model="formData"
          :rules="formRules"
          label-width="120px"
      >
        <el-form-item label="商品名称" prop="goodsName">
          <el-input v-model="formData.goodsName" placeholder="请输入商品名称"/>
        </el-form-item>
        <el-form-item label="所需积分值" prop="pointsNeeded">
          <el-input
              v-model.number="formData.pointsNeeded"
              min="1"
              placeholder="请输入所需积分"
              type="number"
          />
        </el-form-item>
        <el-form-item label="等级限制" prop="levelLimit">
          <el-select
              v-model="formData.levelLimit"
              placeholder="请选择等级限制"
              style="width: 100%"
          >
            <el-option
                v-for="option in levelOptions"
                :key="option.value"
                :label="option.label"
                :value="option.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="库存数量" prop="stock">
          <el-input
              v-model.number="formData.stock"
              min="0"
              placeholder="请输入库存数量"
              type="number"
          />
        </el-form-item>
        <el-form-item label="商品状态" prop="status">
          <el-select v-model="formData.status" placeholder="请选择状态">
            <el-option label="上架" value="1"/>
            <el-option label="下架" value="0"/>
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleSubmit">确定</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<style scoped>
.goods-management-container {
  padding: 20px;
}

.page-header {
  margin-bottom: 20px;
  padding-bottom: 10px;
  border-bottom: 1px solid #eee;
}

.page-header h2 {
  margin: 0;
  font-size: 18px;
  color: #333;
}

.operation-bar {
  padding: 10px 0;
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 15px;
}

.search-group {
  display: flex;
  gap: 10px;
  align-items: center;
}

.search-input {
  width: 300px;
}

.content-card {
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.pagination {
  margin-top: 15px;
  text-align: right;
}
</style>